package com.coder.bike.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.coder.bike.entity.Customer;
import com.coder.bike.entity.Payment;
import com.coder.bike.mapper.CustomerMapper;
import com.coder.bike.service.IBalanceService;
import com.coder.bike.service.IPaymentService;
import com.coder.bike.utils.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class BalanceServiceImpl implements IBalanceService {
    
    private final IPaymentService paymentService;
    private final CustomerMapper customerMapper;
    
    public BalanceServiceImpl(IPaymentService paymentService, CustomerMapper customerMapper) {
        this.paymentService = paymentService;
        this.customerMapper = customerMapper;
    }
    
    @Override
    public Result  rechargeBalance(Integer customerId, BigDecimal amount) {
        // 创建支付订单
        return paymentService.createPayment(customerId, amount, "账户余额充值");
    }
    
    @Override
    @Transactional
    public Result  handlePaymentSuccess(String paymentNo) {
        // 查询支付订单
        Result  paymentResult = paymentService.queryPayment(paymentNo);
        if (!paymentResult.getSuccess()) {
            return Result.fail().setMessage(paymentResult.getMessage());
        }
        
        Payment payment = (Payment) paymentResult.getData();
        if (!"SUCCESS".equals(payment.getStatus())) {
            return Result.fail().setMessage("支付未成功");
        }
        
        // 更新用户余额
        int affected = customerMapper.update(null, 
            new UpdateWrapper<Customer>()
                .setSql("balance = balance + " + payment.getAmount())
                .eq("id", payment.getCustomerId()));
        
        if (affected > 0) {
            return Result.success(true);
        }
        
        return Result.fail().setMessage("更新用户余额失败");
    }
}